package cn.schoolwow.quickdao.module.database.dql.condition.service;

import cn.schoolwow.quickdao.module.database.dql.condition.domain.QueryOption;
import cn.schoolwow.quickdao.module.database.dql.subCondition.domain.SubQueryOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.io.*;

public class CloneConditionFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QueryOption queryOption = (QueryOption) flowContext.checkData("queryOption");

        ByteArrayInputStream bais = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(queryOption);
            oos.close();

            bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            QueryOption cloneQueryOption = (QueryOption) ois.readObject();

            //共享的部分
            cloneQueryOption.queryColumnOption.queryColumnTypeMap = queryOption.queryColumnOption.queryColumnTypeMap;
            cloneQueryOption.queryColumnOption.queryColumnTypeMapping = queryOption.queryColumnOption.queryColumnTypeMapping;
            cloneQueryOption.queryTableOption.entity = queryOption.queryTableOption.entity;
            cloneQueryOption.queryTableOption.fromCondition = queryOption.queryTableOption.fromCondition;
            for(int i=0;i<cloneQueryOption.subQueryOptionList.size();i++){
                SubQueryOption sourceSubQueryOption = cloneQueryOption.subQueryOptionList.get(i);
                SubQueryOption targetSubQueryOption = queryOption.subQueryOptionList.get(i);

                sourceSubQueryOption.subQueryTableOption.joinCondition = targetSubQueryOption.subQueryTableOption.joinCondition;
                sourceSubQueryOption.subQueryJoinTableOption.parentCondition = targetSubQueryOption.subQueryJoinTableOption.parentCondition;
                sourceSubQueryOption.subQueryJoinTableOption.condition = targetSubQueryOption.subQueryJoinTableOption.condition;
            }
            cloneQueryOption.quickFlow = queryOption.quickFlow;
            cloneQueryOption.quickDAOConfig = queryOption.quickDAOConfig;

            bais.close();
            flowContext.putReturnData("cloneQueryOption", cloneQueryOption);
        } finally {
            if (null != bais) {
                try {
                    bais.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public String name() {
        return "克隆Condition接口对象";
    }
}
